package com.nanjing.demo.service;

import cn.hutool.crypto.digest.BCrypt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Date;


/**
 * @author dubiao
 * @date 2020/5/31
 */
public class JwtUserService implements UserDetailsService {

    private PasswordEncoder passwordEncoder;

    public JwtUserService() {
        //默认使用 bcrypt， strength=10
        this.passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    public UserDetails getUserLoginInfo(String username) {
        //从缓存中取出生成token时用的salt
        String salt = "123456ef";
        UserDetails user = loadUserByUsername(username);
        //将salt放到password字段返回
        return User.builder().username(user.getUsername()).password(salt).authorities(user.getAuthorities()).build();
    }

    public String createToken(UserDetails user) {
        //String salt = BCrypt.gensalt();
        //将盐保存在redis中
        String salt = "123456ef";
        Algorithm algorithm = Algorithm.HMAC256(salt);
        //设置1小时后过期
        Date date = new Date(System.currentTimeMillis() + 3600 * 1000);
        return JWT.create()
            .withSubject(user.getUsername())
            .withExpiresAt(date)
            .withIssuedAt(new Date())
            .sign(algorithm);
    }

    @Override
    public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException {
        return User.builder().username("Jack").password(passwordEncoder.encode("password")).roles("USER").build();
    }

    public void deleteUserLoginInfo(String username) {
        //todo 清除数据库或者缓存中登录salt
    }

}
